<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>Common Modules Source: layer/Layer.js</title>

	<!--[if lt IE 9]>
	<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.simplex.css">

</head>

<body>

<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
	<div class="navbar-header">
		<a class="navbar-brand" href="index.html">Common Modules</a>
		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
        </button>
	</div>
	<div class="navbar-collapse collapse" id="topNavigation">
		<ul class="nav navbar-nav">
			
			<li class="dropdown">
				<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="Base.html">Base</a></li><li><a href="Event.html">Event</a></li><li><a href="Html.html">Html</a></li><li><a href="Internal.html">Internal</a></li><li><a href="ol.Overlay.Popup.html">ol.Overlay.Popup</a></li>
				</ul>
			</li>
			
			<li class="dropdown">
				<a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="global.html#addClass">addClass</a></li><li><a href="global.html#addListener">addListener</a></li><li><a href="global.html#arrayRemove">arrayRemove</a></li><li><a href="global.html#clear">clear</a></li><li><a href="global.html#create">create</a></li><li><a href="global.html#createHidden">createHidden</a></li><li><a href="global.html#empty">empty</a></li><li><a href="global.html#EventType">EventType</a></li><li><a href="global.html#findListener">findListener</a></li><li><a href="global.html#firstUpperToCase">firstUpperToCase</a></li><li><a href="global.html#get">get</a></li><li><a href="global.html#getChildByTagName">getChildByTagName</a></li><li><a href="global.html#getClass">getClass</a></li><li><a href="global.html#getDomEventKey">getDomEventKey</a></li><li><a href="global.html#getElementsByClassName">getElementsByClassName</a></li><li><a href="global.html#getListeners">getListeners</a></li><li><a href="global.html#getrandom">getrandom</a></li><li><a href="global.html#getStyle">getStyle</a></li><li><a href="global.html#getuuid">getuuid</a></li><li><a href="global.html#hasClass">hasClass</a></li><li><a href="global.html#isObject">isObject</a></li><li><a href="global.html#isString">isString</a></li><li><a href="global.html#layerConfigDefautls">layerConfigDefautls</a></li><li><a href="global.html#listen">listen</a></li><li><a href="global.html#listenOnce">listenOnce</a></li><li><a href="global.html#logo">logo</a></li><li><a href="global.html#OL_Style_Type">OL_Style_Type</a></li><li><a href="global.html#remove">remove</a></li><li><a href="global.html#removeClass">removeClass</a></li><li><a href="global.html#removeListener">removeListener</a></li><li><a href="global.html#removeListeners">removeListeners</a></li><li><a href="global.html#setClass">setClass</a></li><li><a href="global.html#splitWords">splitWords</a></li><li><a href="global.html#stamp">stamp</a></li><li><a href="global.html#toBack">toBack</a></li><li><a href="global.html#toFront">toFront</a></li><li><a href="global.html#trim">trim</a></li><li><a href="global.html#unListen">unListen</a></li><li><a href="global.html#unlistenAll">unlistenAll</a></li><li><a href="global.html#unListenByKey">unListenByKey</a></li><li><a href="global.html#upperFirstChart">upperFirstChart</a></li>
				</ul>
			</li>
			
		</ul>
        
            <div class="col-sm-3 col-md-3">
                <form class="navbar-form" role="search">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">
                        <div class="input-group-btn">
                            <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button>
                        </div>
                    </div>
                </form>
            </div>
        
	</div>

</div>
</div>


<div class="container" id="toc-content">
<div class="row">

	
	<div class="col-md-12">
	
		<div id="main">
			

		<h1 class="page-title">Source: layer/Layer.js</h1>
    
<section>
    <article>
        <pre
            class="sunlight-highlight-javascript linenums">import {
    ol
} from '../constants'
import mix from '../utils/mixin'
import Style from '../style/Style'

class Layer extends mix(Style) {
    constructor(map) {
        super();
        this.map = map || null;
        if (!this.map) {
            throw new Error('缺少地图对象！')
        }
    }

    /**
     * 通过layerName获取图层
     * @param layerName
     * @returns {*}
     */
    getLayerByLayerName(layerName) {
        try {
            let targetLayer = null;
            if (this.map) {
                let layers = this.map.getLayers().getArray();

                targetLayer = this.getLayerInternal(layers, 'layerName', layerName)
            }
            return targetLayer;
        } catch (e) {
            console.log(e);
        }
    }

    /**
     * 内部处理获取图层方法
     * @param layers
     * @param key
     * @param value
     * @returns {*}
     */
    getLayerInternal(layers, key, value) {
        let _target = null
        if (layers.length > 0) {
            layers.every(layer => {
                if (layer instanceof ol.layer.Group) {
                    let layers = layer.getLayers().getArray()
                    _target = this.getLayerInternal(layers, key, value)
                    if (_target) {
                        return false
                    } else {
                        return true
                    }
                } else if (layer.get(key) === value) {
                    _target = layer
                    return false
                } else {
                    return true
                }
            })
        }
        return _target
    }

    /**
     * 通过键名键值获取图层集合（注意键名键值必须是set(key, value)）
     * @param key
     * @param value
     */
    getLayersArrayByKeyValue(key, value) {
        try {
            let targetLayers = []
            if (this.map) {
                let layers = this.map.getLayers().getArray()
                targetLayers = this.getLayersArrayInternal(layers, key, value)
            }
            return targetLayers
        } catch (e) {
            console.log(e)
        }
    }
    /**
     * 根据相关键值键名获取图层集合
     * @param layers
     * @param key
     * @param value
     * @returns {Array}
     */
    getLayersArrayInternal(layers, key, value) {
        let _target = []
        if (layers.length > 0) {
            layers.forEach(layer => {
                if (layer instanceof ol.layer.Group) {
                    let layers = layer.getLayers().getArray()
                    let _layer = this.getLayersArrayInternal(layers, key, value)
                    if (_layer) {
                        _target = _target.concat(_layer)
                    }
                } else if (layer.get(key) === value) {
                    _target.push(layer)
                }
            })
        }
        return _target
    }
    /**
  * 通过要素获取图层
  * @param feature
  * @returns {*}
  */
    getLayerByFeatuer(feature) {
        let tragetLayer = null
        if (this.map) {
            if (feature instanceof ol.Feature) {
                let layers = this.map.getLayers().getArray()
                layers.every(layer => {
                    if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource) {
                        let source = layer.getSource()
                        if (source.getFeatures) {
                            let features = source.getFeatures()
                            features.every(feat => {
                                if (feat === feature) {
                                    tragetLayer = layer
                                    return false
                                } else {
                                    return true
                                }
                            })
                        }
                        return false
                    } else if (layer &amp;&amp; layer instanceof ol.layer.Group) {
                        let layers = layer.getLayers().getArray()
                        layers.every(layer => {
                            if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource) {
                                let source = layer.getSource()
                                if (source.getFeatures) {
                                    let features = source.getFeatures()
                                    features.every(feat => {
                                        if (feat === feature) {
                                            tragetLayer = layer
                                            return false
                                        } else {
                                            return true
                                        }
                                    })
                                }
                                return true
                            } else {
                                return true;
                            }
                        })
                    }
                    else {


                        return true
                    }
                })
            } else {
                throw new Error('传入的不是要素!')
            }
        }
        return tragetLayer
    }

    /**
     * 创建临时图层
     * @param layerName
     * @param params
     * @returns {*}
     */
    creatVectorLayer(layerName, params) {
        try {
            if (this.map) {
                let vectorLayer = this.getLayerByLayerName(layerName);
                if (!(vectorLayer instanceof ol.layer.Vector)) {
                    vectorLayer = null;
                }
                if (!vectorLayer) {
                    if (params &amp;&amp; params.create) {
                        vectorLayer = new ol.layer.Vector({
                            layerName: layerName,
                            params: params,
                            layerType: 'vector',
                            source: new ol.source.Vector({
                                wrapX: false
                            }),
                            style: new ol.style.Style({
                                fill: new ol.style.Fill({
                                    color: 'rgba(67, 110, 238, 0.4)'
                                }),
                                stroke: new ol.style.Stroke({
                                    color: '#4781d9',
                                    width: 2
                                }),
                                image: new ol.style.Circle({
                                    radius: 7,
                                    fill: new ol.style.Fill({
                                        color: '#ffcc33'
                                    })
                                })
                            })
                        });
                    }
                }
                if (this.map &amp;&amp; vectorLayer) {
                    if (params &amp;&amp; params.hasOwnProperty('selectable')) {
                        vectorLayer.set("selectable", params.selectable);
                    }
                    this.map.addLayer(vectorLayer);
                }
                return vectorLayer;
            }
        } catch (e) {
            console.log(e);
        }
    }

    /**
     * 创建专题图层
     * @param layerName
     * @param params
     * @returns {*}
     */
    creatTitleLayer(layerName, params) {
        let titleLayer = null;
        if (this.map) {
            let serviceUrl = params['serviceUrl'];
            if (!serviceUrl) return null;
            titleLayer = new ol.layer.Tile({
                layerName: layerName,
                layerType: 'title',
                source: new ol.source.TileArcGISRest({
                    url: serviceUrl,
                    params: params,
                    wrapX: false
                }),
                wrapX: false
            });
            this.map.addLayer(titleLayer)
        }
        return titleLayer;
    }

    /**
     * 创建ImageWMSLayer
     * @param layerName
     * @param params
     * @returns {string}
     */
    createImageWMSLayer(layerName, params) {
        let layer = this.getLayerByLayerName(layerName)
        if (!(layer instanceof ol.layer.Image)) {
            layer = null
        } else if ((layer instanceof ol.layer.Image) &amp;&amp; !(params['addLayer'] === false)) {
            this.map.removeLayer(layer)
            layer = null
        }
        if (!layer &amp;&amp; params &amp;&amp; params['layerUrl'] &amp;&amp; params['create']) {
            layer = new ol.layer.Image({
                layerName: layerName,
                visible: (params['isVisible'] === false) ? params['isVisible'] : true,
                opacity: (params['opacity'] &amp;&amp; (typeof params['opacity'] === 'number')) ? params['opacity'] : 1,
                source: new ol.source.ImageWMS({
                    url: params['layerUrl'],
                    crossOrigin: (params['crossOrigin'] ? params['crossOrigin'] : undefined),
                    params: {
                        LAYERS: params['layers'], // require
                        STYLES: params['style'] ? params['style'] : '',
                        VERSION: params['version'] ? params['version'] : '1.3.0',
                        WIDTH: params['width'] ? params['width'] : 256,
                        HEIGHT: params['height'] ? params['height'] : 256,
                        BBOX: params['bbox'], // require
                        SRS: (params['srs'] ? params['srs'] : 'EPSG:3857'),
                        CRS: (params['srs'] ? params['srs'] : 'EPSG:3857'),
                        REQUEST: params['request'] ? params['request'] : 'GetMap',
                        TRANSPARENT: true,
                        TILED: (params['tiled'] === false) ? params['tiled'] : true,
                        TILESORIGIN: (params['tiledsorrigin'] ? params['tiledsorrigin'] : undefined),
                        SERVICE: 'WMS',
                        FORMAT: (params['format'] ? params['format'] : 'image/png'),
                        VIEWPARAMS: (params['viewparams'] ? params['viewparams'] : '')
                    },
                    serverType: 'geoserver',
                    wrapX: false
                })
            })
        }
        if (this.map &amp;&amp; layer &amp;&amp; !(params['addLayer'] === false)) {
            this.map.addLayer(layer)
        }
        return layer
    }

    /**
     * 移除图层
     * @param layerName
     */
    removeLayerByLayerName(layerName) {
        if (this.map) {
            let layer = this.getLayerByLayerName(layerName);
            if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource() &amp;&amp; layer.getSource().clear) {
                layer.getSource().clear();
            }
        }
    }

}

export default Layer</pre>
    </article>
</section>





		</div>
	</div>

	<div class="clearfix"></div>

	

</div>
</div>


    <div class="modal fade" id="searchResults">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Search results</h4>
          </div>
          <div class="modal-body"></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div>


<footer>


	<span class="copyright">
	https://lzw.me.
	</span>

<span class="jsdoc-message">
	Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a>
	
		on Sun Aug 12th 2018
	
	using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>.
</span>
</footer>

<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/toc.js"></script>

    <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script>


<script>
$( function () {
	$( "[id*='$']" ).each( function () {
		var $this = $( this );

		$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
	} );

	$( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () {
		var $this = $( this );

		var example = $this.find( "code" );
		exampleText = example.html();
		var lang = /{@lang (.*?)}/.exec( exampleText );
		if ( lang && lang[1] ) {
			exampleText = exampleText.replace( lang[0], "" );
			example.html( exampleText );
			lang = lang[1];
		} else {
			var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/);
			lang = langClassMatch ? langClassMatch[1] : "javascript";
		}

		if ( lang ) {

			$this
			.addClass( "sunlight-highlight-" + lang )
			.addClass( "linenums" )
			.html( example.html() );

		}
	} );

	Sunlight.highlightAll( {
		lineNumbers : true,
		showMenu : true,
		enableDoclinks : true
	} );

	$.catchAnchorLinks( {
        navbarOffset: 10
	} );
	$( "#toc" ).toc( {
		anchorName  : function ( i, heading, prefix ) {
			return $( heading ).attr( "id" ) || ( prefix + i );
		},
		selectors   : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4",
		showAndHide : false,
		smoothScrolling: true
	} );

	$( "#main span[id^='toc']" ).addClass( "toc-shim" );
	$( '.dropdown-toggle' ).dropdown();

    $( "table" ).each( function () {
      var $this = $( this );
      $this.addClass('table');
    } );

} );
</script>



<!--Navigation and Symbol Display-->


<!--Google Analytics-->



    <script type="text/javascript">
        $(document).ready(function() {
            SearcherDisplay.init();
        });
    </script>


</body>
</html>
